﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Read.Api.Application.Command;
using B.S.BaseData.Read.Api.Dtos;
using MediatR;
using SqlSugar;

namespace B.S.BaseData.Read.Api.Application.CommandHander
{
    public class GetMenuCascadeCommandHander : IRequestHandler<GetMenuCascadeCommand, ApiResult<List<CascadeDto>>>
    {
        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public GetMenuCascadeCommandHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 查询菜单处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<CascadeDto>>> Handle(GetMenuCascadeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<CascadeDto>> result = new ApiResult<List<CascadeDto>>();

            result.Code = ApiEnum.显示成功;
            result.Msg = ApiEnum.显示成功.ToString();
            var list = GetTree(0).ToList();
            result.Data = list;
            return Task.FromResult(result);
        }

        public List<CascadeDto> GetTree(int id)
        {
            var ids = db.Queryable<Menu>().Where(x => x.PId == id).ToList();

            var dtos = mapper.Map<List<CascadeDto>>(ids);

            foreach (var d in dtos)
            {
                d.Children = GetTree(d.Id);
            }

            return dtos;
        }
    }
}
